/**
 * FileName: OrderServerProcessHandler
 * Author:   powersi
 * Date:     2021/2/28 17:35
 * Description:
 */
package com.zm.demo.netty.action.server.handler;

import com.zm.demo.netty.action.common.Operation;
import com.zm.demo.netty.action.common.OperationResult;
import com.zm.demo.netty.action.common.RequestMessage;
import com.zm.demo.netty.action.common.ResponseMessage;
import com.zm.demo.netty.action.util.JsonUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * Description: 
 * Author:      powersi
 * Date:        2021/2/28 17:35
 */
@Slf4j
public class OrderServerProcessHandler extends SimpleChannelInboundHandler<RequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RequestMessage requestMessage) throws Exception {
        Operation operation = requestMessage.getMessageBody();
        OperationResult operationResult = operation.execute();
        log.info(JsonUtil.toJson(operation));
        ResponseMessage responseMessage = new ResponseMessage();
        responseMessage.setMessageHeader(requestMessage.getMessageHeader());
        responseMessage.setMessageBody(operationResult);

        if (ctx.channel().isActive() && ctx.channel().isWritable()){
            ctx.writeAndFlush(responseMessage);
        }else {
            log.error("not writable now, message dropped");
        }
    }
}
